package com.ywjh.inter.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ywjh.inter.entity.InsulinOrderEntity;
import com.ywjh.inter.service.InsulinService;
import com.ywjh.inter.utils.StrUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class InsulinOrder extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6549948806133527326L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=utf-8");

		JSONObject postData = StrUtil.getPostJSON(req);
		String act = postData.getString("act");
		JSONObject data = postData.getJSONObject("data");
		int r = 0;
		String e = "";
		JSONObject json = new JSONObject();
		switch (act) {
		case "set_insulin_order":
			int doc_id = StrUtil.getInt(data.getString("doc_id"), 0);
			String name_array=data.getString("name_array");
			int patient_id=StrUtil.getInt(data.getString("patient_id"), 0);
			String data_array=data.getString("data_array");
			int type = StrUtil.getInt(data.getString("type"), 0);
			String[] name=name_array.split(",");
			String[] datas=data_array.split(",");
			boolean b=InsulinService.getInstance().setInsulinOrder(doc_id,patient_id,type,name,datas);
			if(b) {
				r=1;
			}else {
				e="数据库错误";
			}
			break;
		case "get_insulin_order":
			patient_id = StrUtil.getInt(data.getString("patient_id"), 0);
			type = StrUtil.getInt(data.getString("type"), 0);
			List<InsulinOrderEntity> list = InsulinService.getInstance().getInsulinOrder(patient_id, type);
			JSONArray array = new JSONArray();
			for (InsulinOrderEntity insulinOrderEntity : list) {
				JSONObject d = new JSONObject();
				d.put("name", insulinOrderEntity.getName());
				d.put("data", insulinOrderEntity.getData());
				d.put("doc_id", insulinOrderEntity.getDoc_id());
				d.put("add_time", StrUtil.getYYYYMMDDHHMI(insulinOrderEntity.getAdd_time()));
				d.put("type", insulinOrderEntity.getType());
				d.put("patient_id", insulinOrderEntity.getPatient_id());
				array.add(d);
			}
			json.put("d", array);
			r=1;
			break;
		}
		json.put("r", r);
		json.put("e", e);
		PrintWriter pw = resp.getWriter();
		pw.write(json.toString());
		pw.flush();
		pw.close();
	}
}
